import React, { Component } from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';

import * as moment from 'moment';
import InvoiceType from '@/components/invoiceType';
import { AuthCode, AuthCodeContext } from '@xforceplus/authcode';
import { Row, Col, Button, Modal, Form, Input, Select, Checkbox } from 'antd';
import { getParcel, getExpress, getAlertWaybillNo, getCancelExpress, getRetreatExpressByReceiver, getParcelDetailById, getCountParcel, getCountWait } from '../../module/action';
//------------------------------------------------
import { allGoodsMap, goodsFilter } from '../moduleUtils'
import TableContainer from '../TableContainer'
import DetailHead from '../DetailHead'
import Footers from '../Footers'
// mapping ro func
import { detailHead, tipDetail } from '../mapping.js';
//------------------------------------------------
import './hassend.scss';

const FormItem = Form.Item
const Option = Select.Option
const confirm = Modal.confirm;
const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 6 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 18 },
  },
};


class HasSendDetail extends Component {
  state = {
    courier: { expressName: this.props.detail.expressName, expressLogo: this.props.detail.expressLogo, expressCode: this.props.detail.expressCode },
    checkedTotal: 0, // 已勾选数量, 默认值 0
    selectedRowKeys: [],
    indeterminate: false,//部分
    isAllChecked: false,//全选
    modalChgVisible: false,
    modalReceiveVisible: false,
    confirmInfo: '真的要执行当前操作吗？',
    goodsInfo: {},//总物品信息
    notSignGoodsInfo: {},//没有勾选的物品信息
  }

  componentWillReceiveProps(nextProps) {//父级props变化石调用
    const { cancelExpressSuccess, detail, parcelDetail, logisticsRequestParam, pageParam, orderParam, onClose } = nextProps
    if (parcelDetail.length > 0 && cancelExpressSuccess) {
      this.props.getParcelDetailById(detail.id)
      this.props.getParcel({
        logisticsParcelRequestParam: logisticsRequestParam,
        pageParam: pageParam,
        orderParam: orderParam
      })
      this.props.getCountParcel()
      this.props.getCountWait()
    } else if (parcelDetail.length === 0 && cancelExpressSuccess) {
      this.props.getParcelDetailById(detail.id)
      this.props.getParcel({
        logisticsParcelRequestParam: logisticsRequestParam,
        pageParam: pageParam,
        orderParam: orderParam
      })
      this.props.getCountParcel()
      this.props.getCountWait()
      onClose()
    }
    this.setState({
      selectedRowKeys: [],
      checkedTotal: 0
    })
  }


  cancelOrder = () => {//取消订单
    let that = this
    const { selectedRowKeys, isAllChecked } = this.state
    const { detail } = this.props
    confirm({
      title: "取消快递",
      content: "是否确认取消快递？",
      okText: '确认',
      cancelText: '取消',
      onOk() {
        that.props.getCancelExpress({
          goodsIds: selectedRowKeys,
          isAllSelect: isAllChecked ? 2 : 1,
          parcelId: detail.id,
        })
        that.setState({
          modalChgVisible: false
        })
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  }
  showChangeModal = () => {//修改订单弹窗
    this.props.getExpress()
    const { selectedRowKeys } = this.state
    const { detail, parcelDetail } = this.props
    const goodsInfo = { batchNo: 0, invoiceSheet1: 0, invoiceSheet2: 0, attachment: 0, salesList: 0, goodsIdList: [] }
    const notSignGoods = { batchNo: 0, invoiceSheet1: 0, invoiceSheet2: 0, attachment: 0, salesList: 0, goodsIdList: [] }
    allGoodsMap(parcelDetail, goodsInfo)
    goodsFilter(parcelDetail, selectedRowKeys, notSignGoods)

    this.setState({
      goodsInfo: goodsInfo,
      notSignGoodsInfo: notSignGoods,
      modalChgVisible: true
    })
  }
  cancelModal = () => {//弹窗取消按钮
    this.setState({
      modalChgVisible: false,
      modalReceiveVisible: false
    })
  }
  submitChange = () => {//修改运单号弹窗确定按钮
    const { courier, selectedRowKeys, isAllChecked } = this.state
    const { detail } = this.props
    // console.log(`courier======>`, courier, detail, `selectedRowKeys==>`, selectedRowKeys)
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!values || err) return
      // console.log('submitChange====next>', values)
      this.props.getAlertWaybillNo({
        expressName: courier.expressName,
        expressCode: courier.expressCode,
        expressLogo: courier.expressLogo,
        waybillNo: values.waybillNo,
        goodsIds: selectedRowKeys,
        isAllSelect: isAllChecked ? 2 : 1,
        parcelId: detail.id,
      })
      this.setState({
        modalChgVisible: false
      })
    })
  }

  returnOrder = () => {//退件
    let that = this
    const { selectedRowKeys, isAllChecked } = this.state
    const { detail, parcelDetail } = this.props
    const goodsInfo = { batchNo: 0, invoiceSheet1: 0, invoiceSheet2: 0, attachment: 0, salesList: 0, goodsIdList: [] }
    const notSignGoods = { batchNo: 0, invoiceSheet1: 0, invoiceSheet2: 0, attachment: 0, salesList: 0, goodsIdList: [] }
    // console.log(`parcelDetail======>`, parcelDetail)
    allGoodsMap(parcelDetail, goodsInfo)
    goodsFilter(parcelDetail, selectedRowKeys, notSignGoods)

    confirm({
      title: "是否确认退件?",
      content: <div>
        <p className="modal-cont">
          您勾选了<span className="color-primary">{goodsInfo.batchNo - notSignGoods.batchNo}</span>个批次封面，
                        <span className="color-primary">{goodsInfo.invoiceSheet1 - notSignGoods.invoiceSheet1}</span>张发票联，
                        <span className="color-primary">{goodsInfo.invoiceSheet2 - notSignGoods.invoiceSheet2}</span>张抵扣联，
                        <span className="color-primary">{goodsInfo.attachment - notSignGoods.attachment}</span>个附件，
                        <span className="color-primary">{goodsInfo.salesList - notSignGoods.salesList}</span>个销货清单
                    </p>
      </div>,
      okText: '确认',
      cancelText: '取消',
      onOk() {
        that.props.getRetreatExpressByReceiver({
          isAllSelect: isAllChecked ? 2 : 1,//1部分 2全部
          parcelId: detail.id,
          goodsIds: selectedRowKeys,
          waybillNo: detail.waybillNo
        })
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  }

  showConfirm = (type) => {//判断超时弹窗
    const that = this
    const { selectedRowKeys, isAllChecked } = this.state
    const { detail } = this.props
    if (type) {
      let info = this.state.confirmInfo
      if (type === 'change') { info = "是否确认继续修改？" }
      if (type === 'cancel') { info = "是否确认取消快递？" }
      if (type === 'bounce') { info = "是否确认退件？" }
      this.setState({ confirmInfo: info })
      confirm({
        title: info,
        content: <div>快递签收已超过<span>  30  </span> 天</div>,
        okText: '确认',
        cancelText: '取消',
        onOk() {
          if (type === 'change') {
            that.showChangeModal()
          } else if (type === 'cancel') {
            that.props.getCancelExpress({
              goodsIds: selectedRowKeys,
              isAllSelect: isAllChecked ? 2 : 1,
              parcelId: detail.id,
            })
            that.setState({
              modalChgVisible: false
            })
          } else if (type === 'bounce') {
            that.returnOrder()
          }
        },
        onCancel() {
          console.log('Cancel');
        },
      });
    }
  }

  vilidNumber = (rule, value, callback) => {//效验
    if (!value) { callback(); return }
    const { detail } = this.props
    const { courier } = this.state
    if (rule.field === 'waybillNo' && detail.expressCode === courier.expressCode) {//同快递同运单会效验，其他不会
      if (value === detail.waybillNo) {
        callback('运单号有误，请仔细核对后再填写'); // 校验未通过
        return;
      }
    }
    callback()
  }

  onSelectCompany = (value, option) => {
    const { validateFields } = this.props.form
    this.setState({
      courier: {
        expressCode: value,
        expressName: option.props['data-name'],
        expressLogo: option.props['data-logo']
      },
    });
    setTimeout(() => {//选择快递公司效验运单号，settimeout=0防止setstate没有立即改变而报的错
      validateFields(['waybillNo'], { force: true })
    }, 0)
  }

  onCheckAllChange = (e) => {//底部全选按钮
    const { parcelDetail } = this.props
    this.setState({
      // checkedList: e.target.checked ? plainOptions : [],
      checkedTotal: e.target.checked ? parcelDetail.length : 0,
      indeterminate: false,
      isAllChecked: e.target.checked,
      selectedRowKeys: e.target.checked ? parcelDetail.map(item => item.id) : [],
    });
  }
  //当页部分选中操作
  chgSelectedRowKeys = (selectedRowKeys, selectedRows) => {
    const { parcelDetail } = this.props
    this.setState({
      selectedRowKeys: selectedRowKeys,
      checkedTotal: selectedRowKeys.length,
      isAllChecked: selectedRowKeys.length === parcelDetail.length,
    })
  }

  datePoor = (sDate) => {//判断签收30填
    let sdate = new Date(sDate.replace(/-/g, "/"));
    let now = new Date();
    const days = now.getTime() - sdate.getTime();
    const day = parseInt(days / (1000 * 60 * 60 * 24));
    return day;
  }


  render() {
    const { onClose, sender, parcelDetail, detail, express, userReSource } = this.props;
    const { getFieldDecorator, validateFieldsAndScroll } = this.props.form;
    const { modalChgVisible, modalReceiveVisible, indeterminate, checkedTotal, isAllChecked, selectedRowKeys, courier, goodsInfo, notSignGoodsInfo } = this.state;
    const boolean = selectedRowKeys.length > 0 ? false : true
    const day = this.datePoor(moment(detail.expressSignTime).utcOffset(-360).format('YYYY-MM-DD HH:mm:ss'))
    const btmRight = sender ? <React.Fragment>
      <Button disabled={boolean} onClick={(detail.expressLgtStatus === 10 && day >= 30) ? () => this.showConfirm("change") : this.showChangeModal}>修改运单号</Button>
      <Button disabled={boolean} onClick={(detail.expressLgtStatus === 10 && day >= 30) ? () => this.showConfirm("cancel") : this.cancelOrder}>取消快递</Button>
      {/* <AuthCodeContext.Provider value={{ "authCodes": userReSource }}>
        <AuthCode auth_code={'X00500003'}><Button disabled={boolean} onClick={(detail.expressLgtStatus === 10 && day >= 30) ? () => this.showConfirm("change") : this.showChangeModal}>修改运单号</Button></AuthCode>
        <AuthCode auth_code={'X00500004'}><Button disabled={boolean} onClick={(detail.expressLgtStatus === 10 && day >= 30) ? () => this.showConfirm("cancel") : this.cancelOrder}>取消快递</Button></AuthCode>
      </AuthCodeContext.Provider> */}
    </React.Fragment> :
      // <AuthCodeContext.Provider value={{ "authCodes": userReSource }}>
      //   <AuthCode auth_code={'X00500006'}><Button disabled={boolean} onClick={this.returnOrder} type="primary">退件</Button></AuthCode>
      // </AuthCodeContext.Provider>
      <Button disabled={boolean} onClick={this.returnOrder} type="primary">退件</Button>



    const btmLeft = <React.Fragment>
      <Checkbox
        indeterminate={indeterminate}
        onChange={this.onCheckAllChange}
        checked={isAllChecked}>
        全部全选
                共{checkedTotal}/{parcelDetail && parcelDetail.length}条记录
            </Checkbox>
    </React.Fragment>
    return (
      <React.Fragment>
        <DetailHead dataSource={detail} onClose={onClose} />
        <div className="detail-box">
          <TableContainer chgSelectedRowKeys={this.chgSelectedRowKeys}
            selectedRowKeys={selectedRowKeys}
            dataSource={parcelDetail} />
          <Footers btmLeft={btmLeft} btmRight={btmRight} />
        </div>
        <Modal
          title="修改运单号"
          width="600px"
          visible={modalChgVisible}
          onCancel={this.cancelModal}
          footer={
            <div>
              <Button onClick={this.cancelModal}>取消</Button>
              <Button type="primary" onClick={this.submitChange}>确定</Button>
            </div>}
          wrapClassName="modal-sendIn">
          <p className="modal-cont">
            您勾选了<span className="color-primary">{goodsInfo.batchNo - notSignGoodsInfo.batchNo}</span>个批次封面，
                        <span className="color-primary">{goodsInfo.invoiceSheet1 - notSignGoodsInfo.invoiceSheet1}</span>张发票联，
                        <span className="color-primary">{goodsInfo.invoiceSheet2 - notSignGoodsInfo.invoiceSheet2}</span>张抵扣联，
                        <span className="color-primary">{goodsInfo.attachment - notSignGoodsInfo.attachment}</span>个附件，
                        <span className="color-primary">{goodsInfo.salesList - notSignGoodsInfo.salesList}</span>个销货清单
                    </p>
          <Form>
            <FormItem {...formItemLayout} label="请选择快递公司">
              {getFieldDecorator('company', {
                initialValue: courier.expressName,
              })(
                <Select style={{ width: 250 }} onChange={this.onSelectCompany} >
                  {express.map(item => <Option key={item.expressCode} data-logo={item.expressLogo} data-name={item.expressName}>{item.expressName}</Option>)}
                </Select>
              )}
            </FormItem>
            <FormItem {...formItemLayout} label="运单号">
              {getFieldDecorator('waybillNo', {
                rules: [{ required: true, message: '运单号不能为空!' }, {
                  validator: this.vilidNumber
                }],
              })(<Input style={{ width: 250 }} placeholder="请输入运单号" />)}
            </FormItem>
          </Form>
        </Modal>
      </React.Fragment>
    );
  }
}

function mapStateToProps(state) {
  const { parcelDetail, express, cancelExpressSuccess, logisticsRequestParam, orderParam, userReSource } = state.logistics;
  return {
    parcelDetail,//包裹详情
    express,//物流公司
    cancelExpressSuccess,
    logisticsRequestParam,
    orderParam,
    userReSource,//用户资源码
  };
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators({
    getParcel,//寄送中，异常，已签收 包裹总数
    getExpress,//获取快递公司
    getAlertWaybillNo,//修改运单号
    getCancelExpress,//取消快递
    getRetreatExpressByReceiver,//退件
    getParcelDetailById,
    getParcel,//寄送中，异常，已签收 包裹总数
    getCountParcel,
    getCountWait
  }, dispatch);
}

export default connect(mapStateToProps, mapDispatchToProps)(Form.create()(HasSendDetail));
